<template>
  <ApiRadioGroup
    @change="handleChange"
    v-model:value="mValue"
    v-if="renderType === 'RadioGroup'"
    :api="apiFun"
  />
  <ApiCheckboxGroup
    @change="handleChange"
    v-model:value="mValue"
    v-else-if="renderType === 'CheckboxGroup'"
    :api="apiFun"
  />
  <ApiSelect @change="handleChange" v-model:value="mValue" v-else :api="apiFun">
    <template #[item]="data" v-for="item in Object.keys($slots)">
      <slot :name="item" v-bind="data || {}"></slot>
    </template>
  </ApiSelect>
</template>
<script setup lang="ts">
  import ApiSelect from './ApiSelect.vue';
  import ApiRadioGroup from './ApiRadioGroup.vue';
  import ApiCheckboxGroup from './ApiCheckboxGroup.vue';
  import { useDictStore } from '@/store/modules/dict';
  import { ref, watch } from 'vue';
  import { isArray } from '@/utils/is';

  const emits = defineEmits(['update:value', 'change']);
  const props = defineProps({
    value: {
      type: [String, Number, Array],
    },
    code: {
      type: String,
    },
    renderType: {
      type: String as PropType<'Select' | 'RadioGroup' | 'CheckboxGroup'>,
      default: 'Select',
    },
    isNeedConvert: {
      // 是否需要转换
      type: Boolean,
      default: false,
    },
  });
  const dictStore = useDictStore();
  /**
   * 将数组转换为字符串
   * @param arr
   */
  const arrToStr = (arr: any) => {
    if (isArray(arr)) {
      return arr.join(',');
    }
    return arr;
  };
  /**
   * 将字符串转换为数组
   * @param str
   */
  const strToArr = (str: any) => {
    if (!str) return [];
    return str.toString().split(',');
  };
  const mValue = ref<any>(props.isNeedConvert ? strToArr(props.value) : props.value);
  const handleChange = (val) => {
    const v = props.isNeedConvert ? arrToStr(val) : val;
    emits('update:value', v);
    emits('change', v);
  };
  watch(
    () => props.value,
    (val) => {
      mValue.value = props.isNeedConvert ? strToArr(val) : val;
    },
  );
  const apiFun: any = () => {
    return dictStore.requestData(props.code as string);
  };
</script>
<style lang="less" scoped></style>
